<?php /* УТФ-8:fix */

// ToDo: вынести в lang-файл информацию об ошибках

class SPIcontroller__media__manage extends SPIcontroller__media
{
    private function safe_gid( $gid, $pid, $mid = 0 )
    {
        return preg_replace( '/[^a-z0-9]/iu', '_', $gid ) . '_' . (int) $pid . ( $mid ? '_'.$mid : '' );
    }

    private function get_crc_of_const_vars( $array )
    {
        ksort( $array );
        foreach( $array as $key => $value )
        {
            $array[$key] = (string) $value;
        }

        $stamp=time().rand(10000,30000);

        return $stamp.':'.md5($stamp.serialize($array));
    }

    private function check_crc_of_const_vars( $array, $crc )
    {
        list( $stamp, $crc ) = explode( ':', $crc );

        ksort( $array );
        foreach( $array as $key => $value )
        {
            $array[$key] = (string) $value;
        }

        return $crc == md5($stamp.serialize($array));
    }

    public function initialize( $gid, $pid, $allow_extensions = null, $attrs = null )
    {
        if( $pid === null )
        {
            $rand = md5( time().rand( 10000, 30000 ) ) . md5( rand( 10000, 30000 ).':'.rand( 1, 32123 ) );
            $gid  = iconv_substr( $gid . '::' . $rand, 0, 48 );
        }

        if( is_array( $attrs ) === false )
        {
            $attrs = array();
        }

        $attrs['limit'] = (int) $attrs['limit'];

        if( $attrs['limit'] <= 0 )
        {
            $attrs['limit'] = 200; // default
        }

        //---------------------------------------------------------------------

        $content = array();
        $content['gid'] = $gid;
        $content['pid'] = (int) $pid;
        $content['media_group_id'] = $this->safe_gid( $gid, $pid );
        $content['upload_max_filesize'] = ini_get( 'upload_max_filesize' );

        //---------------------------------------------------------------------

        if( (string) $allow_extensions === '' )
        {
            $allow_extensions = array();
        }
        elseif( is_array( $allow_extensions ) === false )
        {
            $allow_extensions = explode( ',', $allow_extensions );
        }


        $allow_extensions_fulllist = array();

        foreach( $allow_extensions as $allow_extension )
        {
            if( is_array( $allow_extension ) === true && count( $allow_extension ) > 0 )
            {
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $allow_extension );
            }
            elseif( $allow_extension == $this->PRESET_IMAGES )
            {
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_IMAGE_JPG );
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_IMAGE_GIF );
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_IMAGE_PNG );
            }
            elseif( $allow_extension == $this->PRESET_VIDEOS )
            {
                /*
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_VIDEO_AVI );
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_VIDEO_MPG );
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_VIDEO_WMV );
                */
                $allow_extensions_fulllist = array_merge( $allow_extensions_fulllist, $this->TYPE_VIDEO_FLV );
            }
            elseif( trim( $allow_extension ) != '' )
            {
                $allow_extensions_fulllist[] = trim( $allow_extension );
            }
        }
        $allow_extensions = $allow_extensions_fulllist;
        unset( $allow_extensions_fulllist );

        sort( $allow_extensions );

        //---------------------------------------------------------------------

        $formvars_overall = array();
        $formvars_overall['gid'] = $gid;
        $formvars_overall['pid'] = (int) $pid;
        $formvars_overall['allow_extensions'] = join( ',', $allow_extensions );
        $formvars_overall['limit'] = $attrs['limit'];

        //---------------------------------------------------------------------
        // Items

        $qresult = SPIm::I('media')->select( $gid, $pid );

        $index = 0;
        while( $media_item = $qresult->fetch() )
        {
            $item = array();
            $item['safe_gid']               = $this->safe_gid( $gid, $pid, $media_item['id'] );
            $item['media_group_id']         = $content['media_group_id'];
            $item['allow_extensions']       = $content['allow_extensions'];
            $item['allow_extensions_view']  = join( ', ', $allow_extensions );
            $item['upload_max_filesize']    = $content['upload_max_filesize'];

            //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            $item['link_form_submit'] = $this->pack_link();
            $item['formvars'] = $formvars_overall;
            $item['formvars']['mid'] = $media_item['id'];
            $item['formvars']['action'] = 'modify';
            $item['formvars']['crc'] = $this->get_crc_of_const_vars( $item['formvars'] );

            //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            $item['link_delete_form_submit'] = $this->pack_link();
            $item['delete_formvars'] = $formvars_overall;
            $item['delete_formvars']['mid'] = $media_item['id'];
            $item['delete_formvars']['action'] = 'delete';
            $item['delete_formvars']['crc'] = $this->get_crc_of_const_vars( $item['delete_formvars'] );

            //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            $media_item['index']            = ++$index;

            $media_item['link_etalon']      = SPIm::I('media')->get_public_source_by_media_item(
                                               $media_item
                                            );
            $media_item['link_preview']     = SPIm::I('media')->get_public_source_by_media_item(
                                               $media_item,
                                               array( 'mode' => 'preview' )
                                            );
            $media_item['link_download']    = SPIm::I('media')->get_public_source_by_media_item(
                                               $media_item,
                                               array( 'download' => true )
                                            );

            $item['media_item'] = $media_item;

            //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

            $content['items'][ $media_item['id'] ] = $item;
        }
        $qresult->close();

        //---------------------------------------------------------------------
        // Form for new item

        if( count( $content['items'] ) < $attrs['limit'] )
        {
            $item = array();
            $item['safe_gid']               = $this->safe_gid( $gid, $pid );
            $item['media_group_id']         = $content['media_group_id'];
            $item['allow_extensions']       = $content['allow_extensions'];
            $item['allow_extensions_view']  = join( ', ', $allow_extensions );
            $item['upload_max_filesize']    = $content['upload_max_filesize'];

            $item['link_form_submit']       = $this->pack_link();

            $item['formvars'] = $formvars_overall;
            $item['formvars']['action'] = 'insert';
            $item['formvars']['crc'] = $this->get_crc_of_const_vars( $item['formvars'] );

            $content['form'] = $item;
        }
        else
        {
            $content['form'] = false;
        }

        //---------------------------------------------------------------------

        return $content;
    }

    public function attach_pack_for_newitem( $tmp_media_gid, $new_item_id )
    {
        list( $real_media_gid ) = explode( '::', $tmp_media_gid );

        return SPIm::I('media')->manage->reassign_media_pack( $tmp_media_gid, null, $real_media_gid, $new_item_id );
    }

    public function pack_link( $vars = null )
    {
        return SPIc::I('manage')->link->pack( $this->CONTROLLER_ID, null, $vars );
    }

    public function exec( & $content )
    {
        $data                       = array();
        $data['gid']                = SPI::I('var')->get('gid');
        $data['pid']                = (int) SPI::I('var')->get('pid');
        $data['div_id']             = SPI::I('var')->get('div_id');
        $data['action']             = SPI::I('var')->get('action');
        $data['media_group_id']     = SPI::I('var')->get('media_group_id');

        switch( $data['action'] )
        {
            case 'insert':
            case 'modify':
            {
                list( $status, $result_data ) = $this->exec_savedata( $data['action'], $content, $data );

                if( $status === false )
                {
                    SPIv::I('media')->manage->json_action_response( $data['media_group_id'], $data['div_id'], 'error', $result_data );
                    die();
                }
                else
                {
                    SPIv::I('media')->manage->json_action_response( $data['media_group_id'], $data['div_id'], 'complite', $result_data );
                    die();
                }
                break;
            }

            case 'delete':
            {
                list( $status, $result_data ) = $this->exec_delete( $content, $data );

                if( $status === false )
                {
                    SPIv::I('media')->manage->json_action_response( $data['media_group_id'], $data['div_id'], 'error', $result_data );
                    die();
                }
                else
                {
                    SPIv::I('media')->manage->json_action_response( $data['media_group_id'], $data['div_id'], 'delete_complite', $result_data );
                    die();
                }
                break;
            }
        }

        SPIv::I('media')->manage->json_action_response( $data['media_group_id'], $data['div_id'], 'error', 'Undefined action' );
        die();
    }

    private function exec_savedata( $mode, & $content, & $data )
    {
        $data['mid']                        = (int) SPI::I('var')->get('mid');
        $data['item_title']                 = SPI::I('var')->get('item_title');
        $data['allow_extensions']           = SPI::I('var')->get('allow_extensions');
        $data['limit']                      = (int) SPI::I('var')->get('limit');
        $data['order_index']                = (int) SPI::I('var')->get('order_index');

        //---------------------------------------------------------------------
        // Check CRC of incoming const-vars

        $crc_formvars                       = array();
        $crc_formvars['gid']                = $data['gid'];
        $crc_formvars['pid']                = $data['pid'];
        $crc_formvars['action']             = $data['action'];
        $crc_formvars['allow_extensions']   = $data['allow_extensions'];
        $crc_formvars['limit']              = $data['limit'];

        if( $mode == 'modify' )
        {
            $crc_formvars['mid']     = $data['mid'];
        }

        if(  $this->check_crc_of_const_vars( $crc_formvars, SPI::I('var')->get('crc') ) === false )
        {
            return array( false, 'Wring vars CRC' );
        }

        unset( $crc_formvars );

        //---------------------------------------------------------------------

        if( $mode == 'insert' )
        {
            $mediaItemsCount = SPIm::I('media')->get_count( $data['gid'], $data['pid'] );

            if( $mediaItemsCount >= $data['limit'] )
            {
                return array( false, 'Exceeded the limit of items' );
            }
        }

        //---------------------------------------------------------------------

        $media_attrs = array();
        $media_attrs['is_uploaded'] = false;

        $uploadfile_attrs = SPI::I('var')->get_file('uploadfile');

        if( $uploadfile_attrs !== false )
        {
            $media_attrs['is_uploaded']  = true;
            $media_attrs['width']        = null; // will reset if not assign in downcode
            $media_attrs['height']       = null; // will reset if not assign in downcode
            $media_attrs['extension']    = strtolower( (string) @ array_pop( explode( '.', $uploadfile_attrs['name'] ) ) );

            switch( $uploadfile_attrs['error'] )
            {
                case 0:  /* all good */ break;

                case 1:  return array( false, 'Uploaded file exceeds #1' );
                case 2:  return array( false, 'uploaded file exceeds #2' );
                case 3:  return array( false, 'Uploaded file was only partially uploaded' );
                case 4:  return array( false, 'No file was uploaded' );
                default: return array( false, 'Undefined error' );
            }

            $data['allow_extensions'] = trim( $data['allow_extensions'] );

            if( $data['allow_extensions'] != '' )
            {
                $data['allow_extensions'] = explode( ',', strtolower( $data['allow_extensions'] ) );

                if( in_array( $media_attrs['extension'], $data['allow_extensions'] ) === false )
                {
                    return array( false, array( 'Content is deny ', '('.$media_attrs['extension'].')' ) );
                }
            }
            # else if allow_extensions is empty -> all content types allow

            //---------------------------------------------------------------------

            $is_getimagesize = false;

            if( in_array( $media_attrs['extension'], $this->TYPE_IMAGE_JPG ) ) $is_getimagesize = true;
            if( in_array( $media_attrs['extension'], $this->TYPE_IMAGE_GIF ) ) $is_getimagesize = true;
            if( in_array( $media_attrs['extension'], $this->TYPE_IMAGE_PNG ) ) $is_getimagesize = true;
            if( in_array( $media_attrs['extension'], $this->TYPE_FLASH_SWF ) ) $is_getimagesize = true;

            if( $is_getimagesize )
            {
                $img_attrs = getimagesize( $uploadfile_attrs['tmp_name'] );

                if( $img_attrs !== false )
                {
                    $media_attrs['width']  = $img_attrs[0] ? (int) $img_attrs[0] : null;
                    $media_attrs['height'] = $img_attrs[1] ? (int) $img_attrs[1] : null;
                }
            }

            //---------------------------------------------------------------------
        }
        elseif( $mode == 'insert' )
        {
            return array( false, 'No uploaded data' );
        }

        //---------------------------------------------------------------------

        $description = trim( SPI::I('var')->get('description') );

        //---------------------------------------------------------------------

        if( $mode == 'insert' )
        {
            $data['mid'] = SPIm::I('media')->manage->insert( $data['gid'], $data['pid'], $description, $media_attrs );

            if( $data['mid'] === false )
            {
                return array( false, 'Cannot push record' );
            }

            $mediaItemsCount++;
        }
        else # if 'modify'
        {
            SPIm::I('media')->manage->modify( $data['mid'], $description, $media_attrs, $data['order_index'] );
        }

        //---------------------------------------------------------------------

        if( $media_attrs['is_uploaded'] === true )
        {
            if( SPIm::I('media')->manage->load_file( $data['mid'], $uploadfile_attrs['tmp_name'] ) === false )
            {
                return array( false, 'Cannot load file' );
            }
        }

        //---------------------------------------------------------------------
        // Generate tpl-item data

        $media_data = $this->initialize( $data['gid'], $data['pid'], $data['allow_extensions'], array( 'limit' => $data['limit'] ) );

        $result = array();
        $result['mode'] = $mode;

        if( $mode == 'insert' && $media_data['form'] !== false )
        {
            $result['form_safe_gid'] = $media_data['form']['safe_gid'];
            $result['form_tpldata']  = SPIv::I('media')->manage->render_form( $data['item_title'], $media_data['form'] );
        }
        else
        {
            $result['form_safe_gid'] = false;
            $result['form_tpldata']  = false;
        }

        $result['item_safe_gid'] = $media_data['items'][ $data['mid'] ]['safe_gid'];
        $result['item_tpldata']  = SPIv::I('media')->manage->render_item( $data['item_title'], $media_data['items'][ $data['mid'] ] );

        //---------------------------------------------------------------------

        return array( $data['mid'], $result );
    }

    private function exec_delete( & $content, & $data )
    {
        $data['mid']                        = (int) SPI::I('var')->get('mid');
        $data['item_title']                 = SPI::I('var')->get('item_title');
        $data['allow_extensions']           = SPI::I('var')->get('allow_extensions');
        $data['limit']                      = (int) SPI::I('var')->get('limit');

        //---------------------------------------------------------------------
        // Check CRC of incoming const-vars

        $crc_formvars                       = array();
        $crc_formvars['mid']                = $data['mid'];
        $crc_formvars['gid']                = $data['gid'];
        $crc_formvars['pid']                = $data['pid'];
        $crc_formvars['action']             = $data['action'];
        $crc_formvars['allow_extensions']   = $data['allow_extensions'];
        $crc_formvars['limit']              = $data['limit'];

        if(  $this->check_crc_of_const_vars( $crc_formvars, SPI::I('var')->get('crc') ) === false )
        {
            return array( false, 'Wring vars CRC' );
        }

        unset( $crc_formvars );

        //---------------------------------------------------------------------

        $media_item = SPIm::I('media')->get_by_id( $data['mid'] );

        if( $media_item === false )
        {
            return array( false, 'Undefined media ID' );
        }

        SPIm::I('media')->manage->delete( $data['mid'] );

        //---------------------------------------------------------------------
        // Generate tpl-item data

        $media_data = $this->initialize( $data['gid'], $data['pid'], $data['allow_extensions'], array( 'limit' => $data['limit'] ) );

        $result = array();
        $result['mode'] = $mode;

        if( $media_data['form'] !== false && count( $media_data['items'] ) == $data['limit']-1 )
        {
            $result['form_safe_gid'] = $media_data['form']['safe_gid'];
            $result['form_tpldata']  = SPIv::I('media')->manage->render_form( $data['item_title'], $media_data['form'] );
        }
        else
        {
            $result['form_safe_gid'] = false;
            $result['form_tpldata']  = false;
        }

        //---------------------------------------------------------------------

        return array( true, $result );
    }

    public function delete_group( $gid, $pid )
    {
        return SPIm::I('media')->manage->delete_group( $gid, $pid );
    }
}
